<template>
  <el-row>
    <el-col :span="4" style="height: 90vh;overflow-y: scroll">
      <el-row>
        <el-col :span="24">
          <p class="p">当前题库
            <el-icon class="ic">
              <ArrowRight/>
            </el-icon>
            <span class="sp">{{ sd.database }}</span></p>
        </el-col>
      </el-row>
      <el-menu
          default-active="2"
          class="el-menu-vertical-demo"
      >
        <el-menu-item index="0">
          <el-select v-model="value" class="m-2 sc" placeholder="请选择试卷" size="default">
            <el-option
                v-for="(item,index) in sd.papers"
                :key="index"
                :label="item.name"
                :value="item.name"
            />
          </el-select>
        </el-menu-item>

        <el-menu-item index="1" v-if="value">
          <el-button type="default" class="btn" v-if="!paper" @click="beginExam">开始考试</el-button>
          <el-button type="default" class="btn" v-if="paper" @click="sp.setNum(0)">退出考试</el-button>
          <el-button type="default" class="btn-finish" v-if="paper" @click="finishExam">交卷</el-button>
        </el-menu-item>
        <el-row>
          <el-col :span="23" v-if="paper">
            <div class="div" style="text-align: left">
              <label class="labelt">&nbsp;&nbsp;计时器&nbsp;&nbsp;&nbsp;</label>
              <br>
              <div style="text-align: center">
                <span>倒计时&nbsp;</span>
                <el-icon class="is-loading ic" v-if="!tips">
                  <Stopwatch/>
                </el-icon>
                <el-icon class="ic" v-else>
                  <Stopwatch/>
                </el-icon>
                <br>
                <span class="sp1">
                <span v-if="h">{{ h }}:</span>
                <span v-if="!tips">{{ m }}:</span>
                <span v-if="!tips">{{ s }}</span>
                <span v-if="tips" class="sp2">{{ tips }}</span>
              </span>
                <br>
                <el-tooltip content="暂停考试" placement="bottom" effect="light">
                  <svg t="1696647938842" class="icon" viewBox="0 0 1024 1024" version="1.1"
                       xmlns="http://www.w3.org/2000/svg" p-id="4014" width="20" height="20">
                    <path
                        d="M512 5.12C231.424 5.12 3.584 232.96 3.584 514.048s227.84 507.904 508.416 507.904 508.416-227.328 508.416-508.416S792.576 5.12 512 5.12z m0 941.568c-239.616 0-433.664-194.048-433.664-433.664S272.384 80.384 512 80.384s433.664 194.048 433.664 433.664-194.048 432.64-433.664 432.64z"
                        fill="#F4DCCB" p-id="4015"></path>
                    <path
                        d="M665.088 493.056L382.464 329.728c-15.872-9.216-35.84 2.048-35.84 20.48v326.144c0 18.432 19.968 29.696 35.84 20.48l282.112-162.816c16.384-9.216 16.384-32.256 0.512-40.96z"
                        fill="#FF9D4D" p-id="4016"></path>
                  </svg>
                </el-tooltip>

                <el-tooltip content="停止考试" placement="bottom" effect="light">
                  <svg t="1696648046765" class="icon" viewBox="0 0 1024 1024" version="1.1"
                       xmlns="http://www.w3.org/2000/svg" p-id="7905" width="20" height="20">
                    <path
                        d="M661.247 857.615H362.753c-108.002 0-196.368-88.366-196.368-196.368V362.753c0-108.002 88.366-196.368 196.368-196.368h298.494c108.002 0 196.368 88.366 196.368 196.368v298.494c0 108.002-88.366 196.368-196.368 196.368z"
                        fill="#FF7B15" p-id="7906"></path>
                  </svg>
                </el-tooltip>

                <br>
                <el-progress
                    :text-inside="true"
                    :stroke-width="20"
                    :percentage="percent"
                    status="exception"
                    class="progress"
                    :color="color"
                />
                <br>
              </div>
            </div>
          </el-col>
        </el-row>
        <el-row v-if="paper" class="mg">
          <el-col :span="23">
            <div class="div-anwser">
              <label class="labelt">&nbsp;&nbsp;答题卡&nbsp;&nbsp;&nbsp;</label>
              <br>
              <br>
              <div class="div-anwser-inner">
                <el-button :type="item[1].length===0 ? 'info' : 'primary'" round class="btn-anwser" @click="setNum(index)"
                           v-for="(item,index) in qe.anwser">{{ index + 1 }}
                </el-button>

              </div>


              <br>
            </div>
          </el-col>
        </el-row>
        <el-row v-if="paper" class="mg">
          <el-col :span="23">
            <div class="div" style="text-align: left">
              <label class="labelt">&nbsp;&nbsp;试卷信息&nbsp;&nbsp;&nbsp;</label>
              <br>
              <br>
              <el-icon class="ic1">
                <PieChart/>
              </el-icon>
              <label class="label">题量：<span class="sp3">{{ paper.question_volume }}题</span></label>
              <br>
              <el-icon class="ic1">
                <Calendar/>
              </el-icon>
              <label class="label">考试日期：<span class="sp3">{{ paper.exam_date }}</span></label>
              <br>
              <el-icon class="ic1">
                <MagicStick/>
              </el-icon>
              <label class="label">题型描述</label>
              <br>
              <span class="sp3" v-for="(item,index) in paper.question_type" :key="index">&nbsp;&nbsp;<el-icon
                  class="ic2"><Help/></el-icon>{{ item.description }} <br></span>
              <br>
            </div>
          </el-col>
        </el-row>

      </el-menu>

    </el-col>
    <el-col v-if="!paper & !showStatistics" :span="20" class="exam">
      <el-row>
        <el-col :span="22" :offset="1" class="mg">
          <el-icon style="color: #535bf2">
            <Warning/>
          </el-icon>
          等待选择试卷开考...

        </el-col>
      </el-row>
    </el-col>
    <el-col v-if="!paper & showStatistics" :span="20" class="exam">
      <el-row>
        <el-col :span="22" :offset="1" class="mg">
          <div class="div-detail">
            <label class="labelt">&nbsp;&nbsp;本次考试统计数据&nbsp;&nbsp;&nbsp;</label>
            <div class="div-detail_1">
              <el-row>
                <el-col :span="12">
                  <span>开始时间：{{ statisticData[0].begin_time }}</span><br>
                  <span>交卷时间：{{ showData.exam_date }}</span><br>
                </el-col>
                <el-col :span="12">
                  <div style="text-align: right">
                    <span>客观题得分：</span>
                    <span style="font-size: 50px;font-weight: bolder;color:orange">{{ statisticData[0].right_score_count }}</span><span>/{{ statisticData[0].all_score_count }}</span>
                  </div>
                </el-col>
                <el-col :span="24">
                  <hr>
                </el-col>
              </el-row>
              <el-row class="mg" style="text-align: center">
                <el-col :span="6">
                  <el-statistic title="题量" :value="showData.detial.length"/>
                </el-col>
                <el-col :span="6">
                  <el-statistic :value="statisticData[0].over_count">
                    <template #title>
                      <div style="display: inline-flex; align-items: center">
                        完成情况
                      </div>
                    </template>
                    <template #suffix>/{{ showData.detial.length }}</template>
                  </el-statistic>
                </el-col>
                <el-col :span="6">
                  <el-statistic title="客观题正确率" :value="statisticData[0].right_count">
                    <template #suffix>
                      /{{statisticData[0].objective_question_count}}
                    </template>
                  </el-statistic>
                </el-col>
                <el-col :span="6">
                  <el-statistic title="耗时/限时" :value="statisticData[0].total_min">
                    <template #suffix>
                      /{{ paperData.duration }}min
                    </template>
                  </el-statistic>
                </el-col>
              </el-row>
            </div>
          </div>
          <el-row class="mg">
            <el-col :span="24">
              <div class="div-detail">
                <label class="labelt">&nbsp;&nbsp;试卷详情&nbsp;&nbsp;&nbsp;</label>
                <div class="div-detail_1">

                  <div class="demo-collapse">
                    <el-collapse>
                      <el-collapse-item v-for="(item,index) in showData.detial" :name="index">
                        <template #title>
                          <div class="collDiv" v-if="paperData.questions[index].type_number == 3"
                               style="background: #dfe6e9">
                        <span
                            style="margin-left: 1vw;font-weight: bold;color:black">{{ index + 1 }}.{{ paperData.questions[index].question }}</span>
                            <el-tag class="ml-2">主观题</el-tag>
                          </div>

                          <div class="collDiv" v-if="paperData.questions[index].type_number != 3"
                               :style="item[2] ? 'background:#9AECDB' : 'background:#f7d794'">
                        <span
                            style="margin-left: 1vw;font-weight: bold;color:black">{{ index + 1 }}.{{ paperData.questions[index].question }}</span>
                            <el-icon style="color: green" v-if="item[2]"><Select/></el-icon>
                            <el-icon style="color: red" v-if="!item[2]">
                              <CloseBold/>
                            </el-icon>
                          </div>

                        </template>
                        <div class="collDivInner">
                          <el-tag class="ml-2" type="warning">你的答案：</el-tag>
                          &nbsp;
                          &nbsp;
                          <span v-if="item[1] != null">
                        <span v-if="paperData.questions[index].type_number != 4">
                        {{ item[1][1] }}
                        </span>
                        <span v-else>
                          <span v-if="item[1][1] != ''">
                            {{ item[1][1] }}
                          </span>
                          <span v-else>未作答</span>
                        </span>
                        </span>
                          <span v-else>未作答</span>
                          <br>
                          <el-tag class="ml-2">正确答案：</el-tag>
                          &nbsp;
                          &nbsp;
                          <span v-if="item[0] != null">
                        {{ item[0][1] }}
                        </span>
                        </div>
                        <div class="collDivInner_2">
                          <el-tag class="ml-2" type="success">解析：</el-tag>
                          {{paperData.questions[index].correct_answer}}
                        </div>
                      </el-collapse-item>
                    </el-collapse>
                  </div>
                </div>
              </div>


            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-col>
    <el-col v-if="paper" :span="20" class="exam">
      <el-row>
        <el-col :span="22" :offset="1" class="mg">
          <QuickExam_1></QuickExam_1>
        </el-col>
      </el-row>
    </el-col>
  </el-row>
</template>

<script lang="ts" setup>
import {ref, onBeforeUnmount, watch, onUpdated} from 'vue'
import useSelectDatabaseStore from "../../store/selectDatabaseStore";
import usequickExamStore from "../../store/quickExamStore";
import showPageStore from "../../store/showPageStore";
import QuickExam_1 from "./quickExam/QuickExam_1.vue";
import {ElMessage, ElMessageBox} from 'element-plus'
import { some, includes} from 'lodash';

const sd = useSelectDatabaseStore()
const qe = usequickExamStore()
const sp = showPageStore()


const value = ref('')
const paper = ref()
const time = ref(0)
const h = ref(0)
const m = ref(0)
const s = ref(0)
const percent = ref(0)
const color = ref('')
const tips = ref('')
const a = ref(0)
const label = ref("")
const type = ref("")
const showStatistics = ref(false)
const showData = ref()
const paperData = ref()
const statisticData = ref([])
let filename = ""
let beginTime = ""
const beginExam = async () => {
  const now = new Date();
  beginTime = now.getFullYear() + "-" + String(now.getMonth() + 1).padStart(2, '0') + "-" + String(now.getDate()).padStart(2, '0') + " " + String(now.getHours()).padStart(2, '0') + ":" + String(now.getMinutes()).padStart(2, '0');
  tips.value = ""
  for (let i = 0; i < sd.papers.length; i++) {
    if (sd.papers[i].name === value.value) {
      filename = sd.papers[i].file_name
    }
  }
  await myApi.makeFile("exam_" + filename)
  const res = await myApi.getPaper(filename)
  paper.value = res
  time.value = paper.value.duration * 60
  countdown(time.value)
  qe.setPaper(paper)
}

let rights = []
const finishExam = () => {
  compareResult = []
  if (qe.anwser.length != 0) {
    let cs = false
    for (let i = 0; i < qe.anwser.length; i++) {
      if (qe.anwser[i] == null) {
        openElMsg()
        return
      } else {
        cs = true
      }
    }
    if (cs) {
      submitFinishExam()
    }
  } else {
    myApi.alert("你还没有开始做题哦", "info")
  }
}

let compareResult = []
const submitFinishExam = async () => {
  for (let i = 0; i < paper.value.questions.length; i++) {
    rights.push([i, paper.value.questions[i].right, paper.value.questions[i].type_number])
    compareResult.push([])
  }
  for (let i = 0; i < paper.value.questions.length; i++) {
    if (rights[i][2] != 3 && rights[i][2] != 2 && rights[i][2] != 4) {
      let isRight = false
      if (qe.anwser[i] != null) {
        if (JSON.stringify(rights[i][1]) == JSON.stringify(qe.anwser[i][1])) {
          isRight = true
        }
      }
      let tmpList = []
      if (qe.anwser[i][1] != []){
        tmpList = [qe.anwser[i][0],qe.anwser[i][1]]
      }
      compareResult[i] = [[i, rights[i][1]], tmpList, isRight]
      console.log(compareResult[i])
    } else if (rights[i][2] == 2) {
      let isRight = false
      if (qe.anwser[i] != null) {
        if (rights[i][1].length === qe.anwser[i][1].length) {
          if (rights[i][1].every((value, index) => value === qe.anwser[i][1][index])){
            isRight = true
          }
        }
      }
      compareResult[i] = [[i, rights[i][1]], qe.anwser[i], isRight]
    } else if (rights[i][2] == 4) {
      let isRight = false
      if (qe.anwser[i] != null) {
        if (qe.anwser[i][1][0]== rights[i][1][0]) {
          isRight = true
        }
      }
      compareResult[i] = [[i, rights[i][1]], qe.anwser[i], isRight]
    } else if (rights[i][2] == 3) {
      compareResult[i] = [[i, rights[i][1]], qe.anwser[i], true]
    }
  }
  let count4 = 0
  let count5 = 0
  for (let i = 0; i < compareResult.length; i++) {
    if (paper.value.questions[i].type_number != 3){
      if (compareResult[i][2] == true){
        count4 += Number(paper.value.questions[i].score)
      }
      count5 += Number(paper.value.questions[i].score)
    }
  }


  const now = new Date();
  const nowTime = now.getFullYear() + "-" + String(now.getMonth() + 1).padStart(2, '0') + "-" + String(now.getDate()).padStart(2, '0') + " " + String(now.getHours()).padStart(2, '0') + ":" + String(now.getMinutes()).padStart(2, '0');
  const id = Date.now();
  const examData = "{\"begin_time\" :\""+beginTime+"\",\"id\": \"" + id +"\",\"exam_date\": \"" + nowTime + "\",\"detial\": " + JSON.stringify(compareResult) + ",\"right_score\" :" + count4 + ",\"all_right_score\" :"+ count5 +"}"
  console.log(examData)
  await myApi.saveExamData(filename,examData)
  if (localStorage.getItem("exam_d")){
    let exam_d = localStorage.getItem("exam_d");
    let exam_d_json = JSON.parse(exam_d)
    exam_d_json.unshift([paper.value.name,beginTime,filename,id.toString()])
    localStorage.setItem("exam_d",JSON.stringify(exam_d_json))
  }
  else {
    let exam_d_json = [[paper.value.name,beginTime,filename,id.toString()]]
    localStorage.setItem("exam_d",JSON.stringify(exam_d_json))
  }
  paperData.value = paper.value
  paper.value = null
  showStatistics.value = true
  showData.value = JSON.parse(examData)
  let count1 = 0
  let count2 = 0
  let count3 = 0

  for (let i = 0; i < showData.value.detial.length; i++) {
    if (showData.value.detial[i][1] != null){
      if (paperData.value.questions[i].type_number != 4){
        count1++
      }
      else {
        if (showData.value.detial[i][1][1] != ""){
          count1++
        }
      }
    }
    if (paperData.value.questions[i].type_number != 3){
      if (showData.value.detial[i][2] == true){
        count2++
      }
      count3++
    }
  }

  const startTime = new Date(beginTime);
  const endTime = new Date(nowTime);

  const timeDiff = endTime - startTime;

// 计算小时数
  const hours = Math.floor(timeDiff / (1000 * 60 * 60));

// 计算分钟数
  const minutes = Math.floor((timeDiff % (1000 * 60 * 60)) / (1000 * 60));

  const totalMin = hours*60 + minutes;

  let d1 = JSON.parse("{\"over_count\": "+count1+",\"right_count\" :"+count2+",\"objective_question_count\" :"+count3+",\"begin_time\" :\""+beginTime+"\",\"right_score_count\" :"+count4+",\"all_score_count\" :"+count5+ ",\"total_min\" :"+ totalMin+"}")
  statisticData.value.unshift(d1)
  clearTimer()
  qe.setAnwser([])
}

const openElMsg = () => {
  ElMessageBox.confirm(
      '还有题目没有完成，确认交卷吗？',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        submitFinishExam()
        ElMessage({
          type: 'success',
          message: '交卷成功',
        })
      })
      .catch((e) => {
        alert(e)
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
}

let second = null

const countdown = (total) => {
  let totalSeconds = total;
  second = setInterval(() => {
    totalSeconds--;
    percent.value = parseInt(String(totalSeconds / total * 100));
    if (percent.value > 50) {
      color.value = "#00cec9"
    } else if (percent.value <= 50 && percent.value > 10) {
      color.value = "#0984e3"
    } else if (percent.value <= 10) {
      color.value = "#ff7675"
    }
    const hours = Math.floor(totalSeconds / 3600);
    const minutes = Math.floor((totalSeconds % 3600) / 60);
    const seconds = totalSeconds % 60;
    h.value = Number(hours.toString().padStart(2, '0'));
    m.value = Number(minutes.toString().padStart(2, '0'));
    s.value = Number(seconds.toString().padStart(2, '0'));
    if (totalSeconds === 0) {
      clearTimer()
    }
  }, 1000);
}

const clearTimer = () => {
  clearInterval(second);
  second = null;
  tips.value = "考试时间到咯"
}

onBeforeUnmount(() => {
  clearTimer()
  qe.setAnwser([])
});

const setNum = (num) => {
  qe.setNum(num)
}
</script>

<style>
.p {
  padding-left: 1vw;
  padding-right: 1vw;
}

.ic {
  font-size: small
}

.ic1 {
  font-size: small;
  margin-left: 1vw;
  margin-right: 1vw;
  color: green;
}

.ic2 {
  font-size: small;
  margin-left: 1vw;
  margin-right: 0.5vw;
  color: deepskyblue;
}

.sp {
  color: gray;
}

.btn {
  width: 100%;
  background: linear-gradient(90deg, rgba(0, 228, 255, 1) 0%, rgba(170, 222, 129, 1) 100%);
  color: white;
  font-weight: bold;
}

.btn-finish {
  width: 100%;
  background: linear-gradient(90deg, rgba(159, 180, 58, 1) 0%, rgba(29, 253, 243, 1) 50%, rgba(102, 69, 252, 1) 100%);
  color: white;
  font-weight: bold;

}

.sc {
  width: 100%;
}

.div {
  border: lightgray 1px solid;
  border-radius: 20px;
  text-align: center;
  width: 100%;
  font-weight: bold;
}

.div-anwser {
  border: lightgray 1px solid;
  border-radius: 20px;
  width: 100%;
  font-weight: bold;


}

.div-anwser-inner {
  max-height: 30vh;
  overflow-y: scroll;
}

.progress {
  width: 100%;
}

.sp1 {
  color: orange;
}

.sp2 {
  color: red;
}

.label {
  font-weight: bold;
  color: gray;
}

.sp3 {
  color: gray;
  font-weight: normal;
}

.labelt {
  background: linear-gradient(90deg, rgba(0, 228, 255, 1) 0%, rgba(129, 222, 216, 1) 100%);
  border-bottom-right-radius: 50px;
  border-top-left-radius: 50px;
  color: white;
  font-weight: bolder;
}

.btn-anwser {
  margin-left: 10px;
  margin-top: 10px;
}

.exam {
  background-color: whitesmoke;
  height: 90vh;
  overflow-y: scroll;
  border-radius: 20px
}

.collDiv {
  width: 100%;
  text-align: left;
  border-radius: 20px;
  background: green;
  height: 90%;
}
.collDivInner{
  padding: 15px;
}
.collDivInner_2{
  padding: 15px;
  max-height: 10vh;
  overflow-y: scroll;
  background: #dcdde1;
  border-radius: 20px;
}
.div-detail{
  border-radius: 20px;
  background: white
}
.div-detail_1{
  padding: 10px;
}
</style>
